<?php

namespace app\index\controller;

use app\data\model\ActOrder;
use app\index\service\LoginUserService;
use think\admin\Controller;
use think\Validate;

class BaseController extends Controller
{

    
    protected $batchValidate = false;
    protected function initialize()
    {
        $this->ifLogin = LoginUserService::ifLogin();
        $this->user = LoginUserService::get();
        if($this->ifLogin){
            $this->is_new  = ActOrder::where('buy_user_id',LoginUserService::get('id'))->count() ==0 ? true : false;
        }else{
            $this->is_new = false;
        }
    }   

    /**
     * 抛出异常处理
     *
     * @param string $msg 异常消息
     * @param integer $code 异常代码 默认为0
     * @param string $exception 异常类
     *
     * @throws Exception
     */
    protected function exception($msg, $code = 0, $exception = '')
    {
        $e = $exception ?: '\think\Exception';
        throw new $e($msg, $code);
    }


    protected function needLogin()
    {
        if(!LoginUserService::ifLogin()){
            if($this->request->isAjax()){
                $this->error('请登录后访问！');
            }else{
                $this->redirect('/');
            }
        }
    }


            /**
     * 验证数据
     * @access protected
     *
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     *
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = false)
    {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
            $v     = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }

        $v->message($message);

        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(true);
        }

        return $v->failException(true)->check($data);
    }

}